package com.lucy.nepu.module.property.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Validator;
import com.lucy.common.constant.HttpStatus;
import com.lucy.common.domain.ResponseDTO;
import com.lucy.nepu.loader.PeriodLoader;
import com.lucy.nepu.module.property.entity.Property;
import com.lucy.nepu.module.property.lib.PropertyDict;
import com.lucy.nepu.module.property.lib.PropertyDictService;
import com.lucy.nepu.module.property.params.PropertyCreateParams;
import com.lucy.nepu.module.property.params.PropertyQueryParams;
import com.lucy.nepu.module.property.params.PropertyUpdateParams;
import com.lucy.nepu.module.property.service.PropertyService;
import com.lucy.nepu.module.property.utils.PropertyUtil;
import com.lucy.nepu.utils.ValidUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("nepu")
@Api(tags = "知识产权")
public class PropertyController {

    @Autowired
    PropertyService service;

    @Autowired
    PropertyDictService dictService;

    @Autowired
    PeriodLoader periodLoader;

//    @PostMapping("properties/storage")
//    @FormLock(lockKey = "PEOPERTY_STORE",needLogin = true)
//    @ApiOperation(value = "暂存记录",notes = "")
//    public ResponseDTO<Object> setStorage(@RequestBody NepuPropertyAddDTO dto){
//        Long userId = StpUtil.getLoginIdAsLong();
//        NepuDraft draft = new NepuDraft();
//        draft.setFormId(ResearchTypeConst.PROPERTY);
//        draft.setStatus(1);
//        draft.setUserId(userId);
//        draft.setFormJsonStr(JsonUtil.obj2String(dto));
//        return ResponseDTO.succData(draftService.saveOne(draft));
//    }
//
//    @GetMapping("properties/storage")
//    @ApiOperation(value = "获取最新暂存")
//    public ResponseDTO<Object> getStorage(){
//        Long userId = StpUtil.getLoginIdAsLong();
//        Optional<NepuDraft> draftOp = draftService.getLastDraft(userId,ResearchTypeConst.PROPERTY);
//        if (!draftOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
//        NepuDraft draft = draftOp.get();
//        return ResponseDTO.succData(JsonUtil.string2Obj(draft.getFormJsonStr(),NepuPropertyAddDTO.class));
//    }
//
//    @GetMapping("properties/storage/all")
//    @ApiOperation(value = "获取全部暂存")
//    public ResponseDTO<Object> getAllStorage(){
//        Long userId = StpUtil.getLoginIdAsLong();
//        List<NepuDraft> drafts = draftService.getFormAllDrafts(userId,ResearchTypeConst.PROPERTY);
//        return ResponseDTO.succData(drafts);
//    }


    @PostMapping(value = "properties")
    @ApiOperation(value = "新建记录",notes = "")
    public ResponseDTO<Object> saveOne(@RequestBody @Validated PropertyCreateParams params){
        // 1. 获取当前登录用户ID -- 自动拦截未登录用户
        String operator = StpUtil.getLoginIdAsString();
        // 2. 表单校验
        String errMsg = PropertyUtil.formValid(params);
        if (!Validator.isEmpty(errMsg)){
            return ResponseDTO.wrap(HttpStatus.BAD_REQUEST,errMsg);
        }
        // 2. 获取当前时间所在周期ID -- 自动拦截不在时间段内的提交
        String periodId = periodLoader.getPeriodId();
        // 3. 获取词典信息
        PropertyDict dict = dictService.getOneUnwrap(params.getPropertyDictId());
        // 4. 写入记录 并赋值最大工作量
        Property property = new Property();
        property.setPeriodId(periodId);
        property.setStatus(1);
        BeanUtil.copyProperties(params,property, CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        property.setWorkload(dict.getWorkloadMax());
        Property saveRes = service.saveOne(property);
        return ResponseDTO.succData(saveRes);
    }

    @PutMapping(value = "properties")
    @ApiOperation(value = "更新单条记录",notes = "")
    public ResponseDTO<Object> updateOne(@RequestBody @Validated PropertyUpdateParams params){
        Optional<Property> propertyOp = service.getOne(params.getId());
        if (!propertyOp.isPresent()){
            return ResponseDTO.wrap(HttpStatus.NOT_FOUND);
        }
        Property property =  propertyOp.get();
        BeanUtil.copyProperties(params,property,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        return ResponseDTO.succData(service.updateOne(property));
    }

    @GetMapping(value = "properties/{id}")
    @ApiOperation(value = "查询单条记录",notes = "")
    public ResponseDTO<Property> getOne(@PathVariable("id") String id){
        Optional<Property> entityOp = service.getOne(id);
        return entityOp.map(ResponseDTO::succData).orElseGet(() -> ResponseDTO.wrap(HttpStatus.NOT_FOUND));
    }


    @DeleteMapping(value = "properties/{id}")
    @ApiOperation(value = "删除单条记录",notes = "")
    public ResponseDTO<Object> deleteOne(@PathVariable("id") String id){
        service.deleteOne(id);
        return ResponseDTO.succMsg("删除成功");
    }


    @GetMapping(value = {"properties"})
    @ApiOperation(value = "查询全部",notes = "")
    public ResponseDTO<Object> getAll(PropertyQueryParams params){
        Sort sort;
        if(params.getOrder().equalsIgnoreCase("DESC")){
            sort = Sort.by(Sort.Direction.DESC, params.getSortBy());
        }else {
            sort = Sort.by(Sort.Direction.ASC, params.getSortBy());
        }

        // tips : 页码对应 - 1
        Pageable pageable = PageRequest.of(params.getPageNum() - 1 , params.getPageSize(), sort);

        Property nepuProperty = new Property();
        BeanUtil.copyProperties(params,nepuProperty, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        Example<Property> example = Example.of(nepuProperty);
        return ResponseDTO.succData(service.getAll(pageable,example));
    }

//    @WebLog(module = "nepu-access",operate = MethodTypeConst.UPDATE)
//    @PutMapping("properties/files")
//    @ApiOperation(value = "更新附件信息",notes = "")
//    public ResponseDTO<Object> updateFiles(@RequestBody @Validated FileUpdateDTO dto){
//        Long userId = StpUtil.getLoginIdAsLong();
//        Optional<Object> propertyOp = researchServiceCtl.getById(dto.getMapperId(),ResearchTypeConst.PROPERTY);
//        if (!propertyOp.isPresent()){
//            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
//        }
//        NepuProperty property = (NepuProperty) propertyOp.get();
//        if (!userId.equals(property.getFirstAuthorId())){
//            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"非负责人无法修改");
//        }
//        // 清理之前的附件信息
//        nepuResearchFileService.deleteEntityLink(property.getId());
//        // 写入新的附件信息
//        List<String> fileIds = dto.getFileIds();
//        nepuResearchFileService.batchBindFile(ResearchTypeConst.PROPERTY,property.getId(),fileIds);
//        // 返回操作信息
//        return ResponseDTO.succMsg("更新成功");
//    }


    @PutMapping("properties/{id}/workload")
    @ApiOperation(value = "修改记录工作量")
    public ResponseDTO<Object> updateWorkload(@PathVariable("id") String id,@RequestParam("workload") Double workload){
        Optional<Property> entityOp = service.getOne(id);
        if (!entityOp.isPresent()){
            return ResponseDTO.wrap(HttpStatus.NOT_FOUND,"未找到对应课题记录");
        }
        Property property =  entityOp.get();
        String dictId = property.getPropertyDictId();
        Optional<PropertyDict> dictOp = dictService.getOne(dictId);
        if (!dictOp.isPresent()){
            return ResponseDTO.wrap(HttpStatus.NOT_FOUND,"未找到课题关联词典记录");
        }
        PropertyDict dict =  dictOp.get();
        if (workload > dict.getWorkloadMax() || workload < dict.getWorkloadMin()){
            return ResponseDTO.wrap(HttpStatus.BAD_REQUEST,"工作量范围错误");
        }
        property.setWorkload(workload);
        // 写入记录
        return ResponseDTO.succData(service.updateOne(property));
    }
}
